package com.djl.sqtg.controller;

import com.alibaba.fastjson.JSONObject;
import com.djl.sqtg.entity.*;
import com.djl.sqtg.service.IGoodsService;
import com.djl.sqtg.service.IUserService;
import com.djl.sqtg.util.DateUtil;
import com.djl.sqtg.util.ItemCFUtil;
import com.djl.sqtg.util.JsonResult;
import com.djl.sqtg.util.TencentCOSUtil;
import com.google.gson.JsonObject;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("goods")
public class GoodsController extends BaseController{
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IUserService userService;

    @GetMapping({"getAllGoods"})
    public JsonResult<List<Goods>> getAllGoods(){

//        List<Goods> data=goodsService.getAllGoods();
        List<Goods> data=goodsService.getMarketingstatusGoods();
        System.out.println(data);
        return new JsonResult<List<Goods>>(OK,data);
    }

//    模糊查询
    @GetMapping({"getGoodsByKey/{keyword}"})
    public JsonResult<List<Goods>> getGoodsByKey(@PathVariable("keyword") String keyword){
        System.out.println("keyword:"+keyword);
        List<Goods> data=goodsService.getGoodsByKey(keyword);
        System.out.println(data);
        return new JsonResult<List<Goods>>(OK,data);
    }



  /*  @PostMapping({"/getGoodsById"})
    public JsonResult<Goods> getGoodsById(@RequestParam("gid") Integer gid,@RequestParam("uid") Integer uid){
        System.out.println("开始查询gid的商品——————————————"+gid);
        System.out.println("uid——————————————"+uid);
        Goods data=goodsService.getGoodsById(gid);
        System.out.println("商品详情："+data);
        if (uid!=0) {
            System.out.println("uid正常");
//                该用户点击该商品一次，总点击次数增加一
//                  先判断数据库表中是否有该用户，若没有则insert
//                  click == null  说明数据库中无该数据

        Integer click=goodsService.getUserClickNumByUidGid(uid,gid);
        if (click == null){
            goodsService.addUserClick(uid,gid);
        }
//        若有则修改点击次数，加一
        else {
           goodsService.addUserClickNum(uid,gid,click+1);
        }
//        基于item的CF，每当用户点击商品查看详情时就应当相应改变用户对该商品是否点击的状态
        }
        return new JsonResult<Goods>(OK,data);
    }*/

    /*
    * 由于前段使用的uniapp的第三方网络请求$http.post,而这个玩意传递的数据是json格式，哪怕content-type是application/x-www-form-urlencoded也是传递的json数据格式
    * 所以后台使用 @RequestBody接收且用JSONObject定义接收的数据
    * 参数：uid，gid
    * */

    /*
    * 获取商品详情
    * 基于itemCF的商品推荐
    * 添加浏览记录
    * */
    @PostMapping({"/getGoodsById"})
    public JsonResult getGoodsById(@RequestBody JSONObject jsonObject){
        Integer  gid =Integer.valueOf(jsonObject.getString("gid"));
        System.out.println("gid:"+gid);
        Integer  uid =Integer.valueOf(jsonObject.getString("uid"));
        System.out.println("uid:"+uid);
//        添加浏览记录
        userService.footprint(uid,gid,DateUtil.getNowTime());

        Goods goods=goodsService.getGoodsById(gid);
//        处理商品详情里面的图片，以,分割出每一张图片
        System.out.println(goods.getGoodsdesc());
        String goodsDesc=goods.getGoodsdesc();
        String[] result = goodsDesc.split(",");
        List goodsPicList=new ArrayList<>();
        for (String r : result) {
            System.out.println("分割结果是: " + r);
            goodsPicList.add(r);
        }
        goods.setGoodsPicList(goodsPicList);
        System.out.println("商品详情："+goods);
        if (uid!=0) {
            System.out.println("uid正常");
//                该用户点击该商品一次，总点击次数增加一
//                  先判断数据库表中是否有该用户，若没有则insert
//                  click == null  说明数据库中无该数据

/*            Integer click=goodsService.getUserClickNumByUidGid(uid,gid);
            User user = goodsService.getUserItemCFByUid(uid);
            if (user!=null){
//                不为空则说明该用户曾经浏览过，
            }else{
//                为空表示该用户以前未浏览过，现在用户正在浏览，所以把该数据添加到itemcf表
                goodsService.addUserToItemCF(uid,gid);
            }*/
/*            if (click == null){
                goodsService.addUserClick(uid,gid);
            }
//        若有则修改点击次数，加一
            else {
                goodsService.addUserClickNum(uid,gid,click+1);
            }*/
//            每当用户点击商品查看详情时默认为用户喜欢该商品
//        基于item的CF，每当用户点击商品查看详情时就应当相应改变用户对该商品是否点击的状态
            //        itemcf代码
            ItemCFUtil itemCFUtil=new ItemCFUtil();
            List gidList = itemCFUtil.getRecommendItemsByItem(uid.longValue(), gid.longValue(), 6);
            if (gidList==null){
                System.out.println("没有该商品的推荐商品");
//                挑选销售量最高的商品返回
                List<Goods> recommendGoods = goodsService.getHotGoods();
                JSONObject data = new JSONObject();
                data.put("goods",goods);
                data.put("recommendGoods",recommendGoods);
                return new JsonResult(OK,data);
            }else {
                System.out.println(gidList.toString());
                List<Goods> recommendGoods = goodsService.getAllGoodsByIds(gidList);
                System.out.println(recommendGoods);
                JSONObject data = new JSONObject();
                data.put("goods",goods);
                data.put("recommendGoods",recommendGoods);
                return new JsonResult(OK,data);
            }
        }
        return new JsonResult(OK,goods);
    }

    @GetMapping({"getAllItemCF"})
    public JsonResult<List<ItemCF>> getAllItemCF(){
        List<ItemCF> data=goodsService.getAllItemCF();
        System.out.println(data);
        return new JsonResult<List<ItemCF>>(OK,data);
    }

    @RequestMapping("getGoodsByPageNum")
    @ResponseBody
    public LayuiResultData getGoodsByPageNum(String keyword, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        System.out.println("进入商品页面函数————————当前页码"+pageNum+"—————————————当前每页数量"+pageSize+"---------关键字："+keyword);
        List<Goods> data;
        Integer count;
        if (keyword==null|| keyword==""){
            System.out.println("总数据......");
            data = goodsService.getGoodsByPageNum((pageNum-1)*10,pageSize);
            count = goodsService.getAllGoodsNum();
        }else{
            System.out.println("search..........");
            data = goodsService.getGoodsBySearch(keyword,(pageNum-1)*10,pageSize);
            count = goodsService.getGoodsBySearchNum(keyword);
        }
        System.out.println("分页查询结果："+data);
        System.out.println("查询数据数量"+count);
        LayuiResultData layuiResultData=new LayuiResultData();
        layuiResultData.setData(data);
        layuiResultData.setCount(count);
        layuiResultData.setPageNum(pageNum);
        layuiResultData.setPageSize(pageSize);
        return  layuiResultData;
    }


    @PostMapping("uplodImgToCos")
    public JSONObject uplodImgToCos(@RequestParam("file") MultipartFile file, @RequestParam("gcid")  Integer gcid) {
        System.out.println("进入商品控制层");
        System.out.println("分类id------>"+gcid);
        String cosdirectory= goodsService.getCosDirectory(gcid);
        System.out.println("腾讯云cos目录名称："+cosdirectory);
        Goods goods=new Goods();
        goods.setGoodsimg(TencentCOSUtil.UploadIMG(file,"goods/"+cosdirectory));
        System.out.println(goods.getGoodsimg());
   /*     carouselService.updateCarouselImg(carousel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "修改成功");
        return jsonObject;*/
        return null;
    }

/*
* layui的upload多文件上传实际上还是单文件上传，他会访问多次controller里面的方法，实际上还是单上传。
* */

    @PostMapping("addGoods")
    public JsonResult addGoods(Goods goods, @RequestParam("files") MultipartFile[] files) {
        System.out.println("进入商品添加控制层");

        System.out.println("files:"+files);
        System.out.println("files.length:"+files.length);
        for (int i=0;i<files.length;i++){
            System.out.println("文件名："+files[i].getOriginalFilename());
            System.out.println("文件大小："+files[i].getSize());
        }
        System.out.println("Goods:"+goods.toString());

//        通过gcid商品分类id获取分类表里面的分类名
        String cosdirectory= goodsService.getCosDirectory(goods.getGcid());
        System.out.println("腾讯云cos目录名称："+cosdirectory);
        String goodsdescUrl=null;
        for (int i=0;i<files.length;i++){
            if (i==0){
                goods.setGoodsimg(TencentCOSUtil.UploadIMG(files[i],"goods/"+cosdirectory));
            }
            else {
                if (i==1){
                    goodsdescUrl=TencentCOSUtil.UploadIMG(files[i],"goods/"+cosdirectory);
                }else{
                    goodsdescUrl=goodsdescUrl+","+TencentCOSUtil.UploadIMG(files[i],"goods/"+cosdirectory);
                }
            }
        }
        System.out.println("goodsdescUrl:"+goodsdescUrl);
        goods.setGoodsdesc(goodsdescUrl);
        goods.setGoodstime(DateUtil.getNowTime());
        System.out.println("goods最终数据："+goods.toString());
        goodsService.addGoods(goods);
        return new JsonResult(OK);
    }


    //删除一个商品
    @GetMapping({"{gid}/delGoodsByGid"})
    public JsonResult delGoodsByGid(@PathVariable("gid") Integer gid){
        System.out.println("删除商品："+gid);
//        goodsService.delGoodsByGid(gid);
        return new JsonResult(OK);
    }
    //批量删除多个商品
    @GetMapping({"{gids}/delManyGoods"})
    public JsonResult delManyGoods(@PathVariable("gids") Integer[] gids){
        System.out.println("批量删除商品：");
        for (int i=0;i<gids.length;i++){
            System.out.println(gids[i]);
        }
//        goodsService.delManyGoods(gids);
        return new JsonResult(OK);
    }

    @GetMapping({"goodsSoldTop"})
    public JsonResult<List<Goods>> goodsSoldTop(){
        List<Goods> data = goodsService.goodsSoldTop();
        System.out.println("商品销量前20");
        System.out.println(data);
        return new JsonResult<List<Goods>>(OK,data);
    }

    /*获取某日前五销售量的商品*/
    @GetMapping({"getTodayHotGoods"})
    public LayuiResultData getTodayHotGoods(){
        System.out.println("进入=============某日前五销售量");
        String today = DateUtil.getToday();
        List<GoodsSales> data = goodsService.getTodayHotGoods(today);
        System.out.println(data);
        LayuiResultData layuiResultData=new LayuiResultData();
        layuiResultData.setData(data);
        layuiResultData.setCount(data.size());
        return layuiResultData;
    }
    /*商品推荐*/
    @GetMapping({"goodsRecommend"})
    public JsonResult goodsRecommend(){
        //1、获取秒杀活动表中商品
        List<LightDeals> lightDealsGoods=goodsService.getLightdealsGoods();
        //2、获取商品营销状态开启的商品
        List<Goods> marketingstatusGoods=goodsService.getMarketingstatusGoods();
        List data = new ArrayList<>();
        data.add(lightDealsGoods); //秒杀活动商品
        data.add(marketingstatusGoods); //营销状态商品
        System.out.println(data);
        return new JsonResult<>(OK,data);
    }

    /*编辑商品*/
    @PostMapping({"editGoods"})
    public JsonResult editGoods( Goods goods){
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println(goods);
        return new JsonResult<>(OK);
    }
//    获取商品评论
    @GetMapping({"getGoodsReview/{gid}"})
    public JsonResult getGoodsReview(@PathVariable Integer gid){
        List<Review> data=goodsService.getGoodsReview(gid);
        System.out.println(data);
        return new JsonResult<>(OK,data);
    }
    //    修改商品上下架状态
    @GetMapping({"updateGoodsState/{gid}/{goodsstate}"})
    public JsonResult updateGoodsState(@PathVariable Integer gid,@PathVariable Integer goodsstate){
        System.out.println(gid+","+goodsstate);
      goodsService.updateGoodsState(gid,goodsstate);
        return new JsonResult<>(OK);
    }

}
